/*
 * Cainiao.com Inc.
 * Copyright (c) 2013-2022 All Rights Reserved.
 */

package site.wtcc.originalfavor.func.common.utils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import okhttp3.Headers.Builder;
import org.springframework.stereotype.Component;
import site.wtcc.originalfavor.func.exception.RestException;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 通过InitializingBean来在项目启动前 初始化okhttp
 *
 * @author hexiaodou
 * @date 2022/09/14 15:44:38
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OkHttpUtil implements InitializingBean {

    private static final MediaType JSON = MediaType.parse("application/json;charset=UTF-8");
    private static final MediaType XML = MediaType.parse("application/xml; charset=utf-8");
    private static final MediaType X_FORM_ENCODE = MediaType.parse("application/x-www-form-urlencoded");

    private final OkHttpClient client;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("OkHttp已就绪...");
    }
    /**
     * get 请求
     *
     * @param url 请求url地址
     * @return string
     */
    public String doGet(String url) {
        return doGet(url, null, null);
    }

    /**
     * get 请求
     *
     * @param url    请求url地址
     * @param params 请求参数 map
     * @return string
     */
    public String doGet(String url, Map<String, String> params) {
        return doGet(url, params, null);
    }

    /**
     * get 请求
     *
     * @param url       请求url地址
     * @param queryBean 请求参数 map
     * @return string
     */
    public String doGet(String url, Object queryBean) {
        Map<String, String> params = new HashMap<>();
        try {
            BeanUtils.copyProperties(queryBean, params);
        } catch (Exception e) {
            log.error("copyProperties error", e);
        }
        return doGet(url, params, null);
    }

    /**
     * get 请求
     *
     * @param url     请求url地址
     * @param headers 请求头字段 {k1, v1 k2, v2, ...}
     * @return string
     */
    public String doGet(String url, String[] headers) {
        return doGet(url, null, headers);
    }

    /**
     * get 请求
     *
     * @param url     请求url地址
     * @param params  请求参数 map
     * @param headers 请求头字段 {k1, v1 k2, v2, ...}
     * @return string
     */
    public String doGet(String url, Map<String, String> params, String[] headers) {
        StringBuilder sb = new StringBuilder(url);
        if (params != null && !params.keySet().isEmpty()) {
            boolean firstFlag = true;
            for (String key : params.keySet()) {
                if (firstFlag) {
                    sb.append("?").append(key).append("=").append(params.get(key));
                    firstFlag = false;
                } else {
                    sb.append("&").append(key).append("=").append(params.get(key));
                }
            }
        }

        Request.Builder builder = new Request.Builder();
        if (headers != null && headers.length > 0) {
            if (headers.length % 2 == 0) {
                for (int i = 0; i < headers.length; i = i + 2) {
                    builder.addHeader(headers[i], headers[i + 1]);
                }
            } else {
                log.warn("headers's length[{}] is error.", headers.length);
            }

        }

        Request request = builder.url(sb.toString()).build();
        return execute(request);
    }

    /**
     * post 请求
     *
     * @param url    请求url地址
     * @param params 请求参数 map
     * @return string
     */
    public String doPost(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();

        if (params != null && !params.keySet().isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        Request request = new Request.Builder().url(url).post(builder.build()).build();

        return execute(request);
    }

    /**
     * post 请求
     *
     * @param url    请求url地址
     * @param params 请求参数 map
     * @return string
     */
    public String doPost(String url, Map<String, String> params, Map<String, String> headers) {
        FormBody.Builder builder = new FormBody.Builder();
        Builder builder1 = new Builder();

        if (params != null && !params.keySet().isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        if (headers != null && !headers.keySet().isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                builder1.add(entry.getKey(), entry.getValue());
            }
        }
        Request request = new Request.Builder().url(url).headers(builder1.build()).post(builder.build()).build();

        return execute(request);
    }

    /**
     * post 请求
     *
     * @param url    请求url地址
     * @param params 请求参数 map
     * @return string
     */
    public String doPostMap(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();

        if (params != null && !params.keySet().isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        Request request;
        request = new Request.Builder().addHeader("Content-type", "application/x-www-form-urlencoded").url(url)
            .post(builder.build()).build();
        return execute(request);
    }

    /**
     * post 请求, 请求数据为 json 的字符串
     *
     * @param url  请求url地址
     * @param json 请求数据, json 字符串
     * @return string
     */
    public String doPostJson(String url, String json) {
        return executePost(url, json, JSON);
    }

    /**
     * post 请求, 请求数据为 json 的字符串
     *
     * @param url  请求url地址
     * @param json 请求数据, json 字符串
     * @return string
     */
    public String doPostJsonWithHeader(String url, String json, Headers headers) {
        return executeHeaderPost(url, json, headers);
    }

    /**
     * post 请求, 请求数据为 xml 的字符串
     *
     * @param url 请求url地址
     * @param xml 请求数据, xml 字符串
     * @return string
     */
    public String doPostXml(String url, String xml) {
        return executePost(url, xml, XML);
    }

    private String executePost(String url, String data, MediaType contentType) {
        RequestBody requestBody = RequestBody.create(data, contentType);
        Request request;
        request = new Request.Builder().url(url).post(requestBody).build();
        return execute(request);
    }

    private String executeHeaderPost(String url, String data, Headers headers) {
        RequestBody requestBody = RequestBody.create(data, JSON);
        Request request = new Request.Builder().headers(headers).url(url).post(requestBody)
            .build();
        return execute(request);
    }

    private String execute(Request request) {
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (Exception e) {
            log.error("invoke request exception:" + com.alibaba.fastjson.JSON.toJSONString(request), e);
            throw new RestException("网络超时！请刷新后重试~");
        }
        return "";
    }

    /**
     * post 请求上传文件
     *
     * @param url    请求url地址
     * @param params 请求参数 map
     * @return string
     */
    public String doPostMultipart(String url, Map<String, String> params, String fileName, File file) {

        RequestBody fileBody = RequestBody.create(file,
            MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"));
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (params != null && !params.keySet().isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }
        //设置为post请求，url后面为请求路径，header设置请求头（可以设置多个），post后面设置请求体
        Request request = new Request.Builder().url(url).post(
            builder.addFormDataPart("file", fileName, fileBody).build()).build();

        return execute(request);
    }
}
